﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using AmkeniCrossLoginApplication.Data_Access;
using Amkeni_System.Classes;

//Used to send an email
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace Amkeni_System.CO
{
    public partial class Register_User : Security
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            /*if (User.IsInRole("IP"))
            {
                MasterPageFile = "~/MasterPages/Project.Master";
            }
            if (User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/Programme.Master";
            }
            if (User.IsInRole("Administrator"))
            {
                MasterPageFile = "~/MasterPages/CO.Master";
            }
            if (User.IsInRole("IP") && User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/ProgProject.Master";
            }*/
        }

        Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void AddUserButton_Click(object sender, EventArgs e)
        {
            string fName = FirstNameTextBox.Text.Trim();
            string lName = LastNameTextBox.Text.Trim();
            string Email = EmailTextBox.Text.Trim();

            string region = string.Empty;
            string IP_partner = string.Empty;

            //long role = long.Parse(RolesList.SelectedValue.Trim());
            string role = "";
            foreach (ListItem li in RolesListBox.Items)
            {
                if (li.Selected == true)
                {
                    role += li.Text.Trim() + ",";
                }
            }

            foreach (ListItem li in ProjectListBox.Items)
            {
                if (li.Selected == true)
                {
                    IP_partner += li.Value.Trim();
                }
            }

            foreach (ListItem li in RegionListBox.Items)
            {
                if (li.Selected == true)
                {
                    region += li.Value.Trim() + ",";
                }
            }

            string password1 = PasswordTextBox1.Text.Trim();
            bool active = bool.Parse(ActiveList.SelectedValue.Trim());
            bool sendEmailNotification = bool.Parse(SendEmailNotificationList.SelectedValue.Trim());
            //bool isProjectManager = bool.Parse(IsProjectManager.SelectedValue.Trim());
            //bool isProgrammeManager = bool.Parse(IsProgrammeManager.SelectedValue.Trim());

            string EncodedPassword = base64Encode(password1);

            try
            {
                var checkExistingUser = (from u in db.users where u.email == Email select u).FirstOrDefault();

                if (checkExistingUser != null)
                {
                    Label8.Text = Email+" has already been added to the database.";
                    return;
                }
                else if (checkExistingUser == null)
                {
                    //============================+
                    //  Add a new User Record     |
                    //============================+
                    user newUser = new user();
                    newUser.first_name = fName;
                    newUser.last_name = lName;
                    newUser.email = Email;

                    //if (ProgrammeList.SelectedValue != "")
                    //{
                    //    programme = long.Parse(ProgrammeList.SelectedValue.Trim());
                    //    newUser.program_id = programme;
                    //}

                    if (IP_partner != string.Empty)
                    {
                        newUser.ip_id = int.Parse(IP_partner);
                    }

                    if (region != string.Empty)
                    {
                        newUser.region = region;
                    }

                    //newUser.is_project_manager = isProjectManager;
                    //newUser.is_programme_manager = isProgrammeManager;
                    newUser.roles = role;
                    newUser.password = EncodedPassword;
                    newUser.active = active;
                    newUser.send_email = sendEmailNotification;

                    db.users.Add(newUser);
                    db.SaveChanges();

                    //===========================================+
                    //  Send Email Message to Welcome People     |
                    //===========================================+

                    //Create the mail message
                    MailMessage mail = new MailMessage();

                    //Add multiple addresses
                    mail.To.Add(new MailAddress(Email, lName));

                    //Set the content
                    mail.Subject = "Welcome to the new Monitoring and Evaluation Reporting System";

                    System.Text.StringBuilder sbuilder = new System.Text.StringBuilder();
                    sbuilder.Append("Hello " + fName + ",").AppendLine().AppendLine();
                    sbuilder.Append("You have recently been added as a user on the new " +
                        "‘UNDP Kenya (Amkeni Wakenya) M&E Reporting System’.").AppendLine().AppendLine();
                    sbuilder.Append("Your current login details are:").AppendLine().AppendLine();
                    sbuilder.Append("Username: " + Email).AppendLine();
                    sbuilder.Append("Default Password: " + password1).AppendLine().AppendLine();
                    sbuilder.AppendLine().AppendLine().AppendLine();
                    sbuilder.Append("You can access the system here: http://undpke01wa001.azurewebsites.net ").AppendLine().AppendLine();
                    sbuilder.Append("Thank you").AppendLine().AppendLine();
                    sbuilder.Append("M&E team").AppendLine().AppendLine().AppendLine();
                    sbuilder.Append("*This email is automatically generated - please do not reply").AppendLine();

                    mail.Body = sbuilder.ToString();

                    //Send the message
                    SmtpClient smtp = new SmtpClient();
                    /****SMTP Client is defined in the Web.Config File****/

                    ServicePointManager.ServerCertificateValidationCallback = delegate(
                            object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                    { return true; }; //Always Accept

                    try
                    {
                        smtp.Send(mail);
                        Label8.Text = fName + " " + lName + " has been added to the system database";
                        FirstNameTextBox.Text = string.Empty;
                        LastNameTextBox.Text = string.Empty;
                        EmailTextBox.Text = string.Empty;
                        //ProgrammeList.SelectedValue = string.Empty;
                        //ProjectListBox.SelectedValue = "";
                        //RolesListBox.SelectedValue = string.Empty;
                    }
                    catch (Exception ex)
                    {
                        Label8.Text = "MSG NOT SENT " + ex.Message + "<br />" + ex.StackTrace;
                    }

                    //=============================================+
                    //                  END SEND MAIL              |
                    //=============================================+

                    //Response.Redirect("~/Amkeni_System/CO/Register_User.aspx");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR adding User "+ex.Message+" "+ex.StackTrace, ex);
            }
        }
    }
}